package com.credithc.signature.facade.controller;

import com.credithc.signature.common.utils.UUIDUtil;
import com.credithc.signature.facade.constant.Constant;
import com.credithc.signature.facade.facadeenum.ResponseEnum;
import com.credithc.signature.facade.ro.RestSignatureReq;
import com.credithc.signature.facade.service.ParamVerifyService;
import com.credithc.signature.facade.service.RestSignService;
import com.credithc.signature.facade.util.ResponseUtil;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 描述：签章Rest服务<br/>
 * 作者：sunyang
 * 创建：2019/5/30 15:33
 * 版本：v1.0.0<br/>
 */
@RestController
@RequestMapping("/api/signaturefacade/v1")
public class SignatureController {

    @Autowired
    private RestSignService restSignService;

    @Autowired
    ParamVerifyService verifyService;


    @ResponseBody
    @PostMapping("signature")
    public String signature(@RequestHeader String encryptKey, @RequestBody @Valid RestSignatureReq restSignatureReq) throws Exception {
        final String signatureSN = UUIDUtil.getUUID();
        MDC.put(Constant.MDC_REQUEST_SN, signatureSN);

        try {
            // 1、校验渠道
            if (!verifyService.existChannel(encryptKey, restSignatureReq)) {
                return ResponseUtil.getResponseMessage(ResponseEnum.ILLEGAL_CHANNEL.getCode());
            }

            // 2、校验模板
            if (!verifyService.existTemplate(restSignatureReq)) {
                return ResponseUtil.getResponseMessage(ResponseEnum.ILLEGAL_TEMPLATE.getCode());
            }

            // 3、校验公章
            if (!verifyService.existSeal(restSignatureReq)) {
                return ResponseUtil.getResponseMessage(ResponseEnum.ILLEGAL_OFFICIAL_SEAL.getCode());
            }

            // 4、校验手写图片大小
            if (!verifyService.checkHandwritingImage(restSignatureReq)) {
                return ResponseUtil.getResponseMessageMap(ResponseEnum.ILLEGAL_HANDWRITING_IMAGE.getCode(), restSignatureReq.getRequestData().getHandWritingErrorMsg()).toString();
            }
            return restSignService.signature(restSignatureReq, signatureSN);
        } finally {
            try {
                MDC.remove(Constant.MDC_REQUEST_SN);
            } catch (Exception e) {
                // 不做处理
            }
        }
    }

}
